package com.spring.learn.controller;

import com.netflix.hystrix.contrib.javanica.annotation.DefaultProperties;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.spring.learn.domain.TbUser;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.util.List;

@RestController
@RequestMapping("/user")
@DefaultProperties(defaultFallback = "defaultFallback")
public class UserController {

    private Logger log = LoggerFactory.getLogger(getClass());

    @Resource
    private RestTemplate restTemplate;
    @Resource
    private DiscoveryClient discoveryClient;

    @GetMapping("/{id}")
    // @HystrixCommand(fallbackMethod = "queryByIdFallback")
    @HystrixCommand
    public String queryById(@PathVariable Long id) {
        if (id == 1) {
            throw new RuntimeException("太忙了");
        }
        String url = "http://provider-service/provider/user/" + id;
        // 获取eureka中注册的user-service实例列表
        // List<ServiceInstance> serviceInstanceList = discoveryClient.getInstances("provider-service");
        // ServiceInstance serviceInstance = serviceInstanceList.get(0);
        // url = "http://" + serviceInstance.getHost() + ":" + serviceInstance.getPort() + "/provider/user/" + id;
        return restTemplate.getForObject(url, String.class);
    }

    public String queryByIdFallback(Long id) {
        log.error("查询用户信息失败。id：{}", id);
        return "对不起，网络太拥挤了！";
    }

    public String defaultFallback() {
        return "默认提示：对不起，网络太拥挤了！";
    }
}
